﻿using NodeCanvas.Framework;
using ParadoxNotion.Design;
using UnityEngine;

namespace Yoozoo.Gameplay.Liberty.AI.Node
{
    [Category("Ggame/Liberty")]
    public class NpcMoveToLockTarget : AIBaseNode
    {
        // 攻击距离
        public BBParameter<float> attackRange = 1.5f;
        // 追击时长限制 (小于0表示不限制)
        public BBParameter<float> limitTime = -1;
        // 目标类型
        public BBParameter<TargetType> moveToTargetType = TargetType.CurrentLockTarget;

        private Vector3 recordLockTargetPosition = Vector3.zero;
        
        protected override void OnExecute()
        {
            // 检测自身状态
            AnimationAgent animationAgent = _entity.viewer.animationAgent;
            if (!animationAgent.CanDoNextAnimation())
            {
                EndAction(false);
                return;
            }
            
            // 目标
            AIEntity targetAIEntity = _entity.battleAgent.GetTarget(moveToTargetType.value);
            if (!targetAIEntity)
            {
                EndAction(true);
                return;
            }
            
            // 检测距离
            Vector3 targetPosition = targetAIEntity.viewer.animator.transform.position;
            Vector3 npcPosition = _entity.viewer.animator.transform.position;
            if (Vector3.Distance(npcPosition, targetPosition) <= attackRange.value)
            {
                EndAction(true);
            }
            else
            {
                recordLockTargetPosition = targetPosition;
                SetDestination(targetPosition);
            }            
        }

        protected override void OnUpdate()
        {
            // 目标
            AIEntity targetAIEntity = _entity.battleAgent.GetTarget(moveToTargetType.value);
            if (!targetAIEntity)
            {
                // 目标丢失
                EndAction(false);
                return;
            }
            // 检测距离
            Vector3 targetPosition = targetAIEntity.viewer.animator.transform.position;
            Vector3 npcPosition = _entity.viewer.animator.transform.position;
            if (Vector3.Distance(npcPosition, targetPosition) <= attackRange.value)
            {
                EndAction(true);
            }
            else
            {
                if(Vector3.Distance(recordLockTargetPosition, targetPosition) > 0.2f)
                {
                    // 目标发生移动
                    recordLockTargetPosition = targetPosition;
                    SetDestination(targetPosition);
                }
                
                if(limitTime.value > 0 && elapsedTime >= limitTime.value)
                {
                    // 追击时长限制
                    EndAction(false);
                }
            }
        }
        
    }
}